<template>
    <el-container>
        <el-main>
            <avue-crud ref="multipleTable" :data="tableData" :option="tableColumns" :page="page" @refresh-change="refresh"
                @search-change="searchChange" @search-reset="searchReset" @filter-change="filterChange" @size-change="sizeChange"
                @current-change="currentChange">
                <template slot="menuLeft">
                    <el-button v-for="(item,index) in btnList" :disabled="item.disabled" :key="index" :type="item.type"
                        :class="{'hide': item.hide}" @click.native="btnclick(item.funName)" size="small">{{ item.label }}</el-button>
                </template>
                <template slot="menu" slot-scope="{row}">
                    <el-button v-if="$store.state.user.permission.user_enabled && row.status === 0 && $store.state.user.userInfo.id != row.id"
                        size="small" type="text" class="successbtn-color" @click.native="enabled(row)">
                        启用
                    </el-button>
                    <el-button v-if="$store.state.user.permission.user_edit" size="small" type="text" class="primarybtn-color"
                        @click.native="edit(row)">
                        编辑
                    </el-button>
                    <el-button v-if="$store.state.user.permission.user_auth && $store.state.user.userInfo.id != Number(row.id)"
                        size="small" type="text" class="primarybtn-color" @click.native="userauth(row)">
                        用户授权
                    </el-button>
                    <el-button v-if="$store.state.user.permission.user_repass && $store.state.user.userInfo.id != row.id"
                        size="small" type="text" class="primarybtn-color" @click.native="rePassword(row)">
                        重置密码
                    </el-button>
                    <el-button v-if="$store.state.user.permission.user_disabled && row.status === 1 && $store.state.user.userInfo.id != row.id"
                        size="small" type="text" class="dangerbtn-color" @click.native="disabled(row)">
                        禁用
                    </el-button>
                    <el-button v-if="$store.state.user.permission.user_del && $store.state.user.userInfo.id != row.id"
                        size="small" type="text" class="dangerbtn-color" @click.native="del(row)">
                        删除
                    </el-button>
                </template>
                <template slot="status" slot-scope="scope">
                    <div v-if="scope.row.status === 1" style="color:#13ce66">启用</div>
                    <div v-if="scope.row.status === 0" style="color:#ff4949">禁用</div>
                </template>
            </avue-crud>
            <el-dialog :title="dialogFormTitle" :destroy-on-close="false" :close-on-click-modal="false" :visible.sync="dialogFormVisible"
                :before-close="handleCloseBindDialogForm" width="500px">
                <div style="height:56vh;overflow:auto">
                    <df-element-form v-if="formHackReset" :formConfig="formConfig[0]" :value="formValue" ref="customForm">
                    </df-element-form>
                </div>
                <el-row slot="footer" class="dialog-footer" style="text-align: center;">
                    <el-button size="small" type="primary" @click="save">保存</el-button>
                    <el-button size="small" @click="dialogFormVisible = false;">取消</el-button>
                </el-row>
            </el-dialog>
            <el-dialog :title="dialogUserAuthTitle" :destroy-on-close="false" :close-on-click-modal="false"
                :visible.sync="dialogUserAuthVisible" :before-close="handleCloseBindDialogForm" width="400px">
                <div style="height:60vh;overflow:auto">
                    <el-checkbox v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                    <el-tree ref="tree" :data="treeData" show-checkbox node-key="id" default-expand-all
                        highlight-current :check-strictly="checkStrictly" :default-checked-keys="treeCheckedData"
                        :expand-on-click-node="false">
                    </el-tree>
                </div>
                <el-row slot="footer" class="dialog-footer" style="text-align: center;">
                    <el-button size="small" type="primary" @click="authSave">授权</el-button>
                    <el-button size="small" @click="dialogUserAuthVisible = false;">取消</el-button>
                </el-row>
            </el-dialog>
        </el-main>
    </el-container>
</template>

<script>
    import {
        api
    } from "@/api/common";
    import {
        getFormConfigData
    } from '@/const/views/system/company/user'
    import SearchCol from '@/components/view/search_col'
    import {
        resolveAllEunuchNodeId
    } from '@/util/util'

    export default {
        components: {
            SearchCol
        },
        data() {
            return {
                formHackReset: true,
                checkStrictly: false,
                checkAll: false,
                editUserID: '',
                editType: '',
                treeData: [], // 菜单树
                treeCheckedData: [],
                formConfig: [], // 表单配置数据
                formValue: {}, // 表单值
                dialogFormVisible: false, // 弹出框显示
                dialogFormTitle: '', // 弹出框标题
                dialogUserAuthVisible: false, // 单位授权弹出框
                dialogUserAuthTitle: '', // 单位授权弹出标题
                page: {
                    // pageSizes: [5, 10, 20, 30, 40],
                    currentPage: 1,
                    total: 0,
                    pageSize: 10
                }, // 分页信息
                searchForm: {}, // 搜索框记录
                filterForm: {}, // 过滤框记录
                btnList: [{ // 按钮
                    hide: !this.$store.state.user.permission.user_add && this.$store.getters.userInfo.user_type ===
                        2,
                    type: "primary",
                    funName: "add",
                    label: "添加"
                }],
                tableData: [], // 表格数据
                tableColumns: { // 表格列配置
                    border: true,
                    stripe: false,
                    showHeader: true,
                    index: false,
                    page: true,
                    align: 'left',
                    menuAlign: 'center',
                    addBtn: false,
                    delBtn: false,
                    editBtn: false,
                    menu: true,
                    menuWidth: 300,
                    // filterBtn:true,
                    columnBtn: false,
                    searchMenuSpan: 4,
                    column: [{ // 表格列
                        prop: "name",
                        label: "用户名"
                    }, {
                        prop: "realname",
                        label: "真实姓名"
                    }, {
                        prop: "email",
                        label: "邮箱"
                    }, {
                        prop: "idcard",
                        label: "身份证号"
                    }, {
                        prop: "mobile",
                        label: "手机号码"
                    }, {
                        prop: "status",
                        label: "状态",
                        slot: true
                    }, {
                        prop: "parent_name",
                        label: "上级组织"
                    }, {
                        label: '快捷搜索',
                        prop: 'keyword',
                        search: true,
                        hide: true,
                        searchPlaceholder: '用户名,姓名,身份证号,手机号码,邮箱'
                    }]
                }
            }
        },
        created() {
            this.getTableList();
            this.getFormConfig();
        },
        methods: {
            // 表格刷新
            refresh() {
                this.getTableList();
            },
            // 搜索
            searchChange(params, done) {
                this.page.currentPage = 1
                this.getTableList(params)
                Object.assign(this.searchForm, params)
                done()
            },
            // 搜索清空
            searchReset() {
                this.page.currentPage = 1
                this.$set(this.searchForm, 'keyword', '')
                this.getTableList()
            },
            // 表格过滤（高级搜索）
            filterChange(result) {
                console.log(result)
                this.getTableList(result)
                this.filterForm = result
            },
            // 分页
            sizeChange(val) {
                this.page.currentPage = 1
                this.page.pageSize = val
                this.getTableList();
            },
            // 当前页
            currentChange(val) {
                this.page.currentPage = val
                this.getTableList();
            },
            // 绑定弹窗子组件的关闭
            handleCloseBindDialogForm() {
                this.dialogFormVisible = false
                this.dialogFormTitle = ''
                this.dialogUserAuthVisible = false
                this.dialogUserAuthTitle = ''
                this.editUserID = ''
                this.treeData = []
                this.editType = ''
            },
            // 树
            getTreeData(params, _url) {
                this.checkAll = false
                let _this = this

                _this.axios.post(_url, params).then((res) => {
                    console.log(res)
                    if (res.data.code == 10000) {
                        _this.treeData = res.data.data.tree
                        // _this.$refs.tree.setCheckedNodes(this.treeData);          
                        // if (res.data.data.checked.length === this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys()).length) {
                        //   _this.checkAll = true
                        // }
                        _this.treeCheckedData = res.data.data.checked
                        if (_this.checkStrictly === false) {
                            _this.treeCheckedData = resolveAllEunuchNodeId(_this.treeData, _this.treeCheckedData,
                                [])
                            _this.$refs.tree.setCheckedKeys(_this.treeCheckedData);
                        }
                    } else {
                        _this.treeData = []
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'error'
                        });
                    }
                }).catch((err) => {
                    _this.treeData = []
                    console.log('调用失败', err)
                })
            },
            handleCheckAllChange() {
                if (this.checkAll) {
                    this.$refs.tree.setCheckedNodes(this.treeData);
                } else {
                    this.$refs.tree.setCheckedKeys([]);
                }
            },
            // 获取表格数据
            getTableList(where) {
                let _this = this,
                    params = {
                        page: this.page.currentPage,
                        limit: this.page.pageSize,
                        companyID: this.$store.state.user.company_id
                    }
                params = Object.assign({}, params, this.searchForm)
                params = Object.assign({}, params, this.filterForm)
                if (where) {
                    params = Object.assign({}, params, where)
                }
                _this.axios.post(api.getUserList, params).then((res) => {
                    console.log(res)
                    if (res.data.code == 10000) {
                        _this.tableData = res.data.data.list
                        _this.page.total = res.data.data.count
                    } else {
                        _this.tableData = []
                        _this.page.total = 0
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'error'
                        });
                    }
                }).catch((err) => {
                    _this.tableData = []
                    _this.page.total = 0
                    console.log('调用失败', err)
                })
            },
            // 获取表单配置
            getFormConfig() {
                var _this = this

                _this.formConfig = getFormConfigData()
                // for (let index = 0; index < _this.formConfig[0].formItemList.length; index++) {
                //   const element = _this.formConfig[0].formItemList[index];
                //   if ((element.type==='select' || element.type==='cascader') && element.optionsUrl.indexOf('companyID') != -1) {
                //     this.$set(_this.formConfig[0].formItemList[index], 'optionsUrl', element.optionsUrl + this.$store.state.user.company_id)
                //   }
                // }
            },
            // 按钮点击（转发）
            btnclick(func) {
                this[func]()
            },
            // 启用
            enabled(row) {
                let url = api.userSts,
                    params = {
                        id: '',
                        status: 1
                    },
                    _this = this

                params.id = row.id

                _this.$confirm('是否确认启用用户?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    _this.handleAxiosFun(url, params)
                }).catch(() => {});
            },
            // 禁用
            disabled(row) {
                let url = api.userSts,
                    params = {
                        id: '',
                        status: 0
                    },
                    _this = this

                params.id = row.id

                _this.$confirm('是否确认禁用用户?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    _this.handleAxiosFun(url, params)
                }).catch(() => {});
            },
            // 添加
            add() {
                this.$set(this.formConfig[0], 'disabled', false)
                for (let index = 0; index < this.formConfig[0].formItemList.length; index++) {
                    const element = this.formConfig[0].formItemList[index];
                    if (element.key === 'name' || element.key === 'idcard') {
                        this.$set(this.formConfig[0].formItemList[index], 'disabled', false)
                    }
                }
                this.formValue = {}
                this.formHackReset = false
                this.$nextTick(() => {
                    this.formHackReset = true
                })
                this.dialogFormVisible = true
                this.dialogFormTitle = '添加用户'
            },
            // 表格行操作列按钮点击（转发）
            rowbtnclick(func, row) {
                this[func](row)
            },
            // 编辑
            async edit(row) {
                let _this = this
                _this.axios.post(api.getUserById, {
                    id: row.id
                }).then((res) => {
                    if (res.data.code == 10000) {
                        _this.$set(_this.formConfig[0], 'disabled', false)
                        for (let index = 0; index < _this.formConfig[0].formItemList.length; index++) {
                            const element = _this.formConfig[0].formItemList[index];
                            if (element.key === 'name' || element.key === 'idcard') {
                                _this.$set(_this.formConfig[0].formItemList[index], 'disabled', true)
                            }
                        }
                        _this.formValue = Object.assign({}, res.data.data)
                        _this.dialogFormVisible = true
                        _this.dialogFormTitle = '编辑【' + row.realname + '】用户'
                        for (const key in _this.formValue) {
                            if (_this.formValue.hasOwnProperty(key)) {
                                const fe = _this.formValue[key];
                                if (key === 'role') {
                                    if (!fe || fe === '' || fe == null) {
                                        _this.$set(_this.formValue, 'role', [])
                                    } else {
                                        let _arr = fe.split(',')
                                        _arr.forEach((item, index) => {
                                            _arr[index] = parseInt(item)
                                        });
                                        _this.$set(_this.formValue, 'role', _arr)
                                    }
                                }
                            }
                        }
                        _this.formHackReset = false
                        _this.$nextTick(() => {
                            _this.formHackReset = true
                        })
                    } else {
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'error'
                        })
                    }
                }).catch((err) => {
                    _this.$message({
                        showClose: false,
                        message: '获取用户详情失败！',
                        type: 'error'
                    })
                    console.log('调用失败', err)
                })
            },
            authSave() {
                let _url = '',
                    params = {
                        auths: this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys()).join(','),
                        userId: this.editUserID
                    }
                if (this.editType === '数据权限') {
                    _url = api.UserDataJurisdictionAuthorize
                } else if (this.editType === '用户权限') {
                    _url = api.authorizeUser
                }

                this.handleAxiosFun(_url, params)
            },
            // 用户权限
            userauth(row) {
                console.log(row);
                this.editUserID = row.id
                this.editType = '用户权限'
                this.dialogUserAuthVisible = true
                this.dialogUserAuthTitle = row.realname
                this.checkStrictly = false
                let params = {
                    userId: row.id,
                    type: 'user'
                }
                this.getTreeData(params, api.getAuthorizeTree)
            },
            rePassword(row) {
                let url = api.userRepwd,
                    _this = this,
                    params = {
                        id: row.id,
                    }

                _this.$confirm('确定要为用户【' + row.realname + '】重置密码?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    _this.handleAxiosFun(url, params)
                }).catch(() => {});
            },
            // 删除
            del(row) {
                let url = api.userRmv,
                    _this = this,
                    params = {
                        id: row.id
                    }

                _this.$confirm('该操作会永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    _this.handleAxiosFun(url, params)
                })
            },
            // 保存
            save() {
                let _this = this,
                    url = api.userCrd,
                    params = this.formValue

                if (params['id'] && params['id'] != '') {
                    params['type'] = 1
                    url = api.userEdt
                }

                _this.handleAxiosFun(url, params)
            },
            lookDetail(row) {
                this.$set(this.formConfig[0], 'disabled', true)
                this.formValue = Object.assign({}, row)
                this.formHackReset = false
                this.$nextTick(() => {
                    this.formHackReset = true
                })
                this.dialogFormVisible = true
                this.dialogFormTitle = '查看【' + row.realname + '】用户'
            },
            // axios接口请求
            handleAxiosFun(url, params, _sucess_callback, _fail_callback) {
                let _this = this

                _this.axios.post(url, params).then((res) => {
                    if (res.data.code == 10000) {
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'success'
                        });
                        if (_sucess_callback && typeof _sucess_callback === 'function') {
                            _sucess_callback()
                        } else {
                            _this.getTableList()
                            _this.handleCloseBindDialogForm()
                        }
                    } else {
                        _this.$message({
                            showClose: false,
                            message: res.data.message,
                            type: 'error'
                        });
                        if (_fail_callback && typeof _fail_callback === 'function') {
                            _fail_callback()
                        }
                    }
                }).catch(() => {
                    _this.$message({
                        showClose: false,
                        message: '调用失败',
                        type: 'error'
                    });
                })
            }
        }
    }
</script>

<style lang="scss">
    .successbtn-color {
        color: #67c23a !important;

        :active {
            color: #5daf34
        }

        :hover {
            color: #85ce61
        }
    }

    .primarybtn-color {
        color: #409EFF !important;

        :active {
            color: #3a8ee6
        }

        :hover {
            color: #66b1ff
        }
    }

    .warningbtn-color {
        color: #e6a23c !important;

        :active {
            color: #cf9236
        }

        :hover {
            color: #ebb563
        }
    }

    .dangerbtn-color {
        color: #f56c6c !important;

        :active {
            color: #dd6161
        }

        :hover {
            color: #f78989
        }
    }
</style>
